﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using CreditAgricole.Framework;

namespace CreditAgricole.CommonElements.Event_Receivers.KnowledgeWFApprovedEventReceiver
{
    /// <summary>
    /// List Workflow Events
    /// </summary>
    public class KnowledgeWFApprovedEventReceiver : SPWorkflowEventReceiver
    {
        //CAML query to retrieve task item based by WF instanceId  
        private const string WfInstanceQuery = @"<Where><Eq><FieldRef Name='WorkflowInstanceID'/><Value Type='GUID'>{0}</Value></Eq></Where>";
        private const string WorkflowTaskList = Constants.WorkflowTasksList;

        /// <summary>
        /// A workflow was completed.
        /// </summary>
        public override void WorkflowCompleted(SPWorkflowEventProperties properties)
        {
            base.WorkflowCompleted(properties);
            
            using (SPSite site = new SPSite(properties.WebUrl))
            using (SPWeb web = site.OpenWeb())
            {
                // Query Workflow Task List  
                SPList wfTaskList = web.Lists[WorkflowTaskList];
                var items = wfTaskList.GetItems(new SPQuery()
                {
                    Query = string.Format(WfInstanceQuery, properties.InstanceId.ToString())
                });

                if (items.Count > 0)
                {
                    Guid listId = new Guid(items[0]["WorkflowListId"].ToString());
                    int itemId = (int)items[0]["WorkflowItemId"];
                    string workflowField = items[0]["WorkflowName"] as string;

                    // Get the List item on which the workflow run  
                    SPListItem item = web.Lists[listId].GetItemById(itemId);

                    // Get the workflow status
                    int status = Convert.ToInt32(item[workflowField]);

                    if (status == 16)
                    {
                        // Approved                        
                        // Move item to Approved documents knowledge list
                        // Get destination library
                        SPDocumentLibrary destLib = web.Lists[Constants.KnowledgeApprovedListTitle] as SPDocumentLibrary;
                        if (destLib != null)
                        {
                            try
                            {
                                // Get file to move
                                byte[] fileBytes = item.File.OpenBinary();
                                string destUrl = destLib.RootFolder.Url + "/" + item.File.Name;

                                // Create new file in destination library, keeping the original created/modified values
                                SPUser author = SPHelper.GetSPUser(item, "Author").User;
                                SPUser editor = SPHelper.GetSPUser(item, "Editor").User;
                                DateTime created = (DateTime)item[SPBuiltInFieldId.Created];
                                DateTime modified = (DateTime)item[SPBuiltInFieldId.Modified];
                                //CALoggingHelper.AddInformationEntry(string.Format("Created : {0} {1}\nModified : {2} {3}", created.ToLongDateString(), created.ToLongTimeString(), modified.ToLongDateString(), modified.ToLongTimeString()));
                                SPFile destFile = destLib.RootFolder.Files.Add(destUrl, fileBytes, item.Properties, author, editor, created, modified, true /*overwrite*/);                                
                                SPListItem li = destFile.Item;
                                li["Created"] = created;
                                li["Modified"] = modified;
                                li.Update();

                                // Delete item from working temp library
                                item.Delete();

                                CALoggingHelper.AddInformationEntry(string.Format("File {0} moved to approved knowledge document library",destFile.Name));
                            }
                            catch (Exception ex)
                            {
                                if (!string.IsNullOrEmpty(ex.Message)) CALoggingHelper.AddErrorEntry(string.Format("Knowledge database - Moving file error :\n\n{0}", ex.Message));
                            }
                        }
                        else
                        {
                            CALoggingHelper.AddErrorEntry(string.Format("Knowledge Database : Unable to move file \"{0}\" to Approved Library. The specified library ({1}) doesn't exists.", item.File.Name, Constants.KnowledgeApprovedListTitle));
                        }
                    }
                    else if (status == 17)
                    {
                        // Rejected
                        // Reset checkbox for submit
                        item[SPCreditAgricoleFieldId.ResubmitWorkflow] = false;
                        item.SystemUpdate();
                    }

                    //else
                    //    CALoggingHelper.AddInformationEntry("Status is not Approved");
                }
                else
                {
                    CALoggingHelper.AddErrorEntry("Knowledge workflow completed but no associated item found.");
                }
            }
        }
    }
}
